<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { InventoryReport } from '@/service/api/inventory';
import { useEcharts } from '@/hooks/common/echarts';

const dataType = ref('num');
const currentMonth = ref($dayjs().valueOf());

const dataTypeOptions = [
  { label: '按数量', value: 'num' },
  { label: '按金额', value: 'money' }
];

// 创建图表
const { domRef, updateOptions } = useEcharts(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  legend: {
    data: ['入库', '出库'],
    top: 5,
    right: 20,
    textStyle: {
      fontSize: 11
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: '20%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [] as string[],
    axisLine: {
      lineStyle: {
        color: '#E0E6ED'
      }
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: '#8C8C8C',
      fontSize: 10
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: false
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      color: '#8C8C8C',
      fontSize: 10
    },
    splitLine: {
      lineStyle: {
        color: '#F0F0F0',
        type: 'dashed'
      }
    }
  },
  series: [
    {
      name: '入库',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      lineStyle: {
        width: 2,
        color: '#52c41a'
      },
      itemStyle: {
        color: '#52c41a'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(82, 196, 26, 0.3)' },
            { offset: 1, color: 'rgba(82, 196, 26, 0.05)' }
          ]
        }
      },
      data: [] as number[]
    },
    {
      name: '出库',
      type: 'line',
      smooth: true,
      symbol: 'circle',
      symbolSize: 4,
      lineStyle: {
        width: 2,
        color: '#1890ff'
      },
      itemStyle: {
        color: '#1890ff'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
            { offset: 1, color: 'rgba(24, 144, 255, 0.05)' }
          ]
        }
      },
      data: [] as number[]
    }
  ]
}));

// 获取图表数据
async function updateChartData() {
  try {
    const date = $dayjs(currentMonth.value);
    const year = date.format('YYYY');
    const month = date.format('MM');

    const response = await InventoryReport.getStockOutInChart({
      year,
      month,
      day: '',
      dataType: dataType.value
    });

    if (response && !response.error && response.data) {
      // transformBackendResponse已经提取了data，直接使用
      const result = response.data;

      // 处理API数据结构，优先使用直接数组格式，回退到series格式
      const categories = result.categories || [];

      if (result.inData && result.outData) {
        const inData = result.inData || [];
        const outData = result.outData || [];

        updateOptions(opts => {
          opts.xAxis.data = categories;
          opts.series[0].data = inData;
          opts.series[1].data = outData;
          return opts;
        });
      } else if (result.series && result.series.length > 0) {
        const inSeries = result.series.find((s: any) => s.name === '入库') || { data: [] };
        const outSeries = result.series.find((s: any) => s.name === '出库') || { data: [] };

        updateOptions(opts => {
          opts.xAxis.data = categories;
          opts.series[0].data = inSeries.data || [];
          opts.series[1].data = outSeries.data || [];
          return opts;
        });
      } else {
        showEmptyStockChart();
      }
    } else {
      showEmptyStockChart();
    }
  } catch {
    // 错误处理 - 在生产环境中可以添加用户友好的提示
    showEmptyStockChart();
  }
}

// 显示空图表
function showEmptyStockChart() {
  updateOptions(opts => {
    opts.xAxis.data = [];
    opts.series[0].data = [];
    opts.series[1].data = [];
    return opts;
  });
}

// 数据类型变化
function handleDataTypeChange() {
  updateChartData();
}

// 日期变化
function handleDateChange() {
  updateChartData();
}

// 初始化数据 - 使用onMounted替代危险的setTimeout
onMounted(() => {
  updateChartData();
});
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- 标题和控制 -->
    <div class="mb-3 flex items-center justify-between">
      <div class="text-sm text-gray-700 font-medium">出入库报表</div>
      <div class="flex items-center space-x-2">
        <NSelect
          v-model:value="dataType"
          size="small"
          class="w-[90px]"
          :options="dataTypeOptions"
          @update:value="handleDataTypeChange"
        />
        <NDatePicker
          v-model:value="currentMonth"
          type="month"
          size="small"
          class="w-[100px]"
          value-format="yyyy-MM-dd"
          @update:value="handleDateChange"
        />
      </div>
    </div>

    <!-- 图表容器 -->
    <div class="flex-1 px-3">
      <div ref="domRef" class="h-full min-h-[200px] w-full"></div>
    </div>
  </div>
</template>
